package logic

import (
	"cartRpc/cache"
	"cartRpc/models"
	"context"
	"errors"
	"fmt"

	"cartRpc/cart"
	"cartRpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCartLogic) AddCart(in *cart.AddCartRequest) (*cart.AddCartResponse, error) {
	// todo: add your logic here and delete this line

	var err error
	var u models.Goods
	var g models.Goods
	var c models.Cart
	u.ID = uint(in.UserId)
	g.ID = uint(in.GoodsId)

	if err = u.GetGoodsById(); err != nil {
		logx.Error("用户信息获取失败")
		return nil, errors.New("用户信息获取失败")
	}
	if err = g.GetGoodsById(); err != nil {
		logx.Error("商品信息获取失败")
		return nil, errors.New("商品信息获取失败")
	}

	if g.Stock < in.Num {
		logx.Error("商品库存不足")
		return nil, errors.New("商品库存不足")
	}

	if cache.IsExistCart(int(in.UserId), int(in.GoodsId)) {
		fmt.Println("购物车中已存在该商品")
		cache.UpdateNum(int(in.UserId), int(in.GoodsId), in.Num)
	} else {
		goodsMap := map[string]interface{}{
			"user_id":     in.UserId,
			"goods_id":    in.GoodsId,
			"num":         in.Num,
			"goods_Name":  g.GoodsName,
			"goods_price": g.GoodsPrice,
		}
		if err = c.AddCart(); err != nil {
			logx.Error("加入购物车失败", err)
			return nil, errors.New("加入购物车失败")
		}
		if err = cache.AddCart(int(in.UserId), int(in.GoodsId), goodsMap); err != nil {
			logx.Error("加入购物车失败", err)
			return nil, errors.New("加入购物车失败")
		}
	}

	return &cart.AddCartResponse{}, nil
}
